package com.hcl.orm.core.dialect.handler.page;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.hcl.orm.core.annotation.DBType;
import com.hcl.orm.core.dialect.SqlDefinition;
import com.hcl.orm.core.dialect.SqlMetadata;
import com.hcl.orm.core.dialect.Signature;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author hucl
 * @projectName hcl-orm
 * @description: Mysql分页翻译
 * @date 2021/8/1116:24
 */
@Component
public class MysqlQueryPageDialectHandler extends QueryPageDialectHandler {
    private static final String SIMPLE_PAGE_QUERY_TMPL = "select * from {} limit ?,?;";

    public MysqlQueryPageDialectHandler() {
        super("Mysql SQL分页方言处理器");
    }

    @Override
    protected void doHandle(SqlDefinition sqlDefinition) {
        final SqlMetadata metadata = sqlDefinition.getSelectedSqlMetadata();
        final Signature signature = sqlDefinition.getSignature();
        if (!signature.isReturnsPage()) {
            return;
        }
        if (!StrUtil.isEmpty(metadata.getRawSql())) {
            sqlDefinition.setPageQueryCountSql(StrUtil.replace(sqlDefinition.getDialectSql().toLowerCase(),
                    FIELDS_PATTERN, m-> " count(*) "));
            sqlDefinition.setDialectSql(StrUtil.concat(true,
                    sqlDefinition.getDialectSql(), " LIMIT ?,?;"));
        } else {
            String tableName = metadata.getTableName();
            sqlDefinition.setPageQueryCountSql(StrUtil.format(SIMPLE_PAGE_QUERY_COUT_TMPL, tableName));
            sqlDefinition.setDialectSql(StrUtil.format(SIMPLE_PAGE_QUERY_TMPL, tableName));
        }
        sqlDefinition.setPageParamFunction((pageParam ->
                new Object[]{(pageParam.getPageNo() - 1) * pageParam.getPageSize(), pageParam.getPageSize()}));
    }
    @Override
    protected List<DBType> getTargetDB() {
        return ListUtil.toList(DBType.MYSQL,DBType.OB_MYSQL);
    }
}
